package com.bbg.amyam.web.util.view;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bbg.amyam.web.util.menu.MenuItem;

public class AmyamLabelGenerate extends AbstractGenerator {
	private static final Log log = LogFactory.getLog(AmyamLabelGenerate.class);

	private static Properties amyamMessages = null;

	public AmyamLabelGenerate(MenuItem item, boolean overwrite) {
		super(item, overwrite);
		try {
			this.initiate();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initiate() throws FileNotFoundException, IOException {
		if (amyamMessages == null) {
			String fileName = super.getAmyamMsgFileName();
			amyamMessages = new Properties();
			amyamMessages.load(new FileInputStream(fileName));
			log.debug("Current amyam messages:");
			dumpProperties();
		}
	}

	@Override
	public void execute() throws IOException {
		String key = "amyam_label_" + this.menuItem.getId();
		String value = amyamMessages.getProperty(key);
		if (!amyamMessages.containsKey(key)) {
			value = StringUtils.replaceChars(this.menuItem.getId(), '_', ' ');
			value = WordUtils.capitalize(value);
			amyamMessages.put(key, value);
		}
	}

	private void dumpProperties() {
		Set<Object> keys = amyamMessages.keySet();
		for (Object key : keys) {
			log.debug(key + "=" + amyamMessages.getProperty((String) key));
		}
	}

	public void saveProperties() throws FileNotFoundException, IOException {

		String fileName = super.getAmyamMsgFileName();

		if (amyamMessages != null) {
			amyamMessages.store(new FileOutputStream(fileName),
					"#############Amyam application properties###########");
			log.debug("Updated amyam messages:");
			dumpProperties();

			log.debug("Propty file updated:" + fileName);
		}
	}

}
